package com.ferry.controller;

import com.ferry.domain.Wall;
import com.ferry.domain.view.WallView;
import com.ferry.service.WallService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
public class ViewController {

    @Autowired
    private WallService wallService;

    @GetMapping("/view")
    public String view(Model model) {

        return getAll(model);
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Long id,Model model) {

        if (id != null) {
            boolean delete = wallService.delete(id);
            if (delete) {
                model.addAttribute("msg","删除成功");
            } else {
                model.addAttribute("msg","删除失败");
            }
        } else {
            model.addAttribute("msg","删除文件为空");
        }

        List<Wall> all = wallService.getAll();

        List<WallView> views = new ArrayList<WallView>();
        for (Wall wall : all) {
            views.add(new WallView(wall));
        }

        model.addAttribute("views",views);

        return "view";
    }
    @GetMapping("/sort/{id}")
    public String sort(@PathVariable Long id,Model model) {
        if (id != null) {
            boolean sort = wallService.addSort(id);
            if (sort) {
                model.addAttribute("msg","增加成功");
            } else {
                model.addAttribute("msg","增加失败");
            }
        } else {
            model.addAttribute("msg","增加文件为空");
        }
        return getAll(model);
    }

    private String getAll(Model model) {
        List<Wall> all = wallService.getAll();

        List<WallView> views = new ArrayList<>();
        for (Wall wall : all) {
            views.add(new WallView(wall));
        }

        model.addAttribute("views",views);

        return "view";
    }

    @PostMapping("/modify/{id}")
    public String modifyName(@PathVariable Long id,String name,Model model) {
        if (id != null) {
            boolean sort = wallService.updateName(id,name);
            if (sort) {
                model.addAttribute("msg","修改成功");
            } else {
                model.addAttribute("msg","修改失败");
            }
        } else {
            model.addAttribute("msg","修改文件为空");
        }
        return getAll(model);
    }
}
